import { formatTime } from '../utils.ts';


// 创建右键菜单
chrome.contextMenus.create({
  id: 'root',
  title: 'Bilibili字幕抓取',
  contexts: ['all']
});

// 创建“下载字幕”子菜单
chrome.contextMenus.create({
  id: 'downloadSubtitle',
  parentId: 'root',
  title: '下载字幕',
  contexts: ['all']
});

// 创建“下载字幕”下的“PDF格式”子菜单
chrome.contextMenus.create({
  id: 'downloadSubtitlePDF',
  parentId: 'downloadSubtitle',
  title: 'PDF',
  contexts: ['all']
});

// 创建“下载字幕”下的“DOC格式”子菜单
chrome.contextMenus.create({
  id: 'downloadSubtitleDOC',
  parentId: 'downloadSubtitle',
  title: 'DOC',
  contexts: ['all']
});

// 创建“去精听”子菜单
chrome.contextMenus.create({
  id: 'goToIntensiveListening',
  parentId: 'root',
  title: '去精听',
  contexts: ['all']
});

// 监听右键菜单点击事件
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'downloadSubtitlePDF') {
    // 处理下载PDF字幕的逻辑
    console.log('下载PDF字幕');
  } else if (info.menuItemId === 'downloadSubtitleDOC') {
    // 处理下载DOC字幕的逻辑
    console.log('下载DOC字幕');
  } else if (info.menuItemId === 'goToIntensiveListening') {
    // 处理去精听的逻辑
    chrome.tabs.sendMessage(tab.id, { type: 'CHECK_SUBTITLES' }, response => {
        if (response && response.subtitles) {
            // 如果字幕信息已经存在，直接传递过去
            chrome.tabs.sendMessage(tab.id, { type: 'SHOW_SUBTITLES', subtitles: response.subtitles });
        } else {
            // 如果字幕信息不存在，则去获取
            chrome.tabs.sendMessage(tab.id, { type: 'FETCH_SUBTITLES' }, fetchResponse => {
                if (fetchResponse.success) {
                    // 获取成功后传递字幕信息
                    chrome.tabs.sendMessage(tab.id, { type: 'SHOW_SUBTITLES', subtitles: fetchResponse.subtitles });
                } else {
                    console.error('获取字幕失败:', fetchResponse.error);
                }
            });
        }
    });
    
    console.log('去精听');
  }
});

// 添加处理字幕请求的消息监听
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'FETCH_SUBTITLES') {
        // 处理获取字幕的请求
        fetchSubtitles(request.aid, request.cid)
            .then(subtitles => sendResponse({ success: true, subtitles }))
            .catch(error => sendResponse({ success: false, error: error.message }));
        return true; // 表示会异步发送响应
    }
});

// 用于存储已处理的请求URL
const processedUrls = new Set();

// // 监听web请求
chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    // 检查是否是字幕文件请求
    if (details.url.startsWith('https://aisubtitle.hdslb.com/bfs/ai_subtitle/prod')) {
      // 检查是否已经处理过该URL
      if (processedUrls.has(details.url)) {
        return;
      }
      // 将URL添加到已处理集合中
      processedUrls.add(details.url); 

      // 发起请求获取字幕内容
      fetch(details.url)
        .then(response => response.json())
        .then(subtitleData => {
          // 将字幕数据存储在localStorage中 
          const key = details.url.split('?')[0];
          chrome.storage.local.set({ [key]: subtitleData.body }).then(() => {
            console.log("Value is set");
          });
        })
        .catch(error => console.error('获取字幕失败:', error));
    }
  },
  {
    urls: ["https://aisubtitle.hdslb.com/bfs/ai_subtitle/prod*"]
  }
);

// 定期清理已处理的URL集合（可选，防止内存占用过大）
setInterval(() => {
  processedUrls.clear();
}, 1000 * 60 * 30); // 每30分钟清理一次

// 获取字幕数据的函数
async function fetchSubtitles(aid, cid) {
    try {
        // 获取字幕列表
        const subtitleListUrl = `https://api.bilibili.com/x/player/v2?aid=${aid}&cid=${cid}`;
        const subtitleListResponse = await fetch(subtitleListUrl);
        const subtitleListData = await subtitleListResponse.json();
        
        // 获取字幕URL
        const subtitles = subtitleListData?.data?.subtitle?.subtitles;
        if (!subtitles || subtitles.length === 0) {
            throw new Error('该视频没有字幕');
        }

        // 获取第一个字幕（通常是中文字幕）
        const subtitleUrl = `https:${subtitles[0].subtitle_url}`;
        const subtitleResponse = await fetch(subtitleUrl);
        const subtitleData = await subtitleResponse.json();

        // 转换字幕格式
        return subtitleData.body.map(item => ({
            startTime: item.from,
            endTime: item.to,
            text: item.content
        }));
    } catch (error) {
        console.error('获取字幕失败:', error);
        throw error;
    }
}

